const STORAGE_KEY = 'gameHistory'

export function getHistory() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed : []
  } catch (e) {
    return []
  }
}

export function addHistoryRecord(record) {
  try {
    const list = getHistory()
    const normalized = {
      id: record?.id || (Date.now() + '_' + Math.random().toString(36).slice(2)),
      roomId: record?.roomId || '',
      roomName: record?.roomName || '',
      endedAt: record?.endedAt || Date.now(),
      durationSeconds: Number(record?.durationSeconds || 0),
      players: Array.isArray(record?.players) ? record.players : [],
      areas: Array.isArray(record?.areas) ? record.areas : [],
      winner: record?.winner || null
    }
    list.unshift(normalized)
    const trimmed = list.slice(0, 50)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed))
  } catch (e) {
    // 忽略
  }
}

export function clearHistory() {
  try {
    localStorage.removeItem(STORAGE_KEY)
  } catch (e) {
    // 忽略
  }
}


